import React, { Component } from 'react';
import axios from '../api'
import mapStyle from './mapStyle'
import _ from 'lodash'

import echarts from 'echarts'

import siteImage from '../images/site.png'

require('echarts/extension-src/bmap/bmap');

export default class Metro extends Component {
  constructor(props) {
    super(props);
    this.init = this.init.bind(this)
  }

  init (option = {}) {
    const myChart = echarts.init(this.ID)
    this.myChart = myChart;
    myChart.setOption(option)
    window.onresize = () => myChart.resize()
  }

  componentDidMount () {
    this.init()
    this.getMetro()
    this.timerID = setInterval(
      () => this.getMetro(),
      15 * 60 * 1000
    );
  }

  componentWillUnmount () {
    clearInterval(this.timerID);
  }

  getMetro () {
    // clearInterval(this.effectID)
    // 获取数据
    axios.get('/metro_info').then(({ data: { center, metro, train, zoom } }) => {
      this.genData(center, metro, train, zoom)
    })
  }

  genData (center, metro, train, zoom) {
    // 地铁线路
    const lines = metro.map(({ site, name }) => ({ name, coords: site.map(({ coordinate }) => coordinate) }))
    // 线路名
    const linesHead = lines.map(({ coords, name }) => ({ name, coords: coords.slice(coords.length - 2) }))
    // 所有站点名
    const sites = [].concat(...metro.map(({ site }) => site.map(({ name, coordinate, value, card }) => ({ name, card, value: coordinate.concat([value]) }))))

    // const genRoute = d => 
    const linesRoute = lines.concat(lines.map(line => Object.assign({}, line, { coords: line.coords.reduceRight((list, item) => list.concat([item]), []) })))

    // 站点去重（换乘站）
    const uniSites = sites.reduce((list, item) => {
      const isExist = list.findIndex(x => x.name === item.name) > -1
      return list.concat(isExist ? [] : [item])
    }, [])

    // 无刷卡进站站点
    // const activeIndex = Math.floor(Math.random() * uniSites.length)
    const activeIndex = 0
    const silentSites = uniSites
    silentSites[activeIndex] = Object.assign({}, silentSites[activeIndex],
      {
        label: {
          show: true,
          formatter: ['{name|{b}}', '{value|站点客流：{@value}}'].join('\n'),
          position: [150, '100%'],
          width: 100,
          height: 100,
          offset: [0, -40],
          align: 'center',
          lineHeight: 50,
          backgroundColor: { image: siteImage },
          rich: {
            name: { fontSize: 14, color: '#fff', verticalAlign: 'bottom' },
            value: { fontSize: 10, color: '#fff', verticalAlign: 'top' }
          }
        }
      })
    // 刷卡进站站点
    const checkinSites = uniSites.filter(({ card }) => card)
    // 列车拥挤程度颜色
    const colors = ['rgba(160, 217, 17,0.5)', 'rgba(250, 219, 20,0.5)', 'rgba(250, 173, 20,0.5)', 'rgba(250, 140, 22,0.5)', 'rgba(250, 84, 28,0.5)', 'rgba(252, 255, 230,0.5)']
    // 列车位置
    const trains = train.filter(({ coords }) => coords.length > 1).map(({ coords, value }) => ({ coords: coords, effect: { color: colors[value] } }))

    const option = {
      bmap: {
        center,
        zoom,
        roam: false,
        mapStyle: mapStyle
      },
      series: [
        {
          name: '地铁线路边框',
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          lineStyle: { color: '#01a6e6', width: 8 },
          data: lines,
          zlevel: 1
        },
        {
          name: '地铁线路',
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          lineStyle: { color: '#040e29', width: 6, opacity: 1 },
          data: lines,
          zlevel: 2
        },
        {
          name: '地铁线路名',
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: false,
          data: linesHead,
          lineStyle: { color: '#00BAFF', opacity: 1, width: 0, },
          label: {
            show: true,
            position: 'end',
            distance: 50,
            formatter: '{b}',
            align: 'right',
            color: '#00BAFF',
            fontSize: 24,
            borderColor: '#0668BA',
            borderWidth: 1,
            borderRadius: 3,
            padding: [9, 28]
          },
          zlevel: 50
        },
        {
          name: '站点',
          type: 'scatter',
          coordinateSystem: 'bmap',
          data: silentSites,
          symbolSize: val => Math.log10(val[2]) * 4,
          itemStyle: { color: '#00BAFF' },
          zlevel: 41
        }, {
          name: '刷卡进站效果',
          type: 'effectScatter',
          coordinateSystem: 'bmap',
          data: checkinSites,
          label:{show:false, formatter:'{b}'},
          symbolSize: val => Math.log10(val[2]) * 4,
          rippleEffect: { brushType: 'fill', scale: 4 },
          itemStyle: { color: 'rgba(0, 186, 255, 0.5)' },
          zlevel: 42
        }, {
          name: '地铁运行效果',
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          data: trains,
          lineStyle: { width: 0 },
          effect: {
            period: 15*60,
            show: true,
            symbol: 'react',
            symbolSize: [6, 10],
            loop: true
          },
          animation: true,
          zlevel: 11
        },
        {
          name: '地铁运行高亮效果',
          type: 'lines',
          coordinateSystem: 'bmap',
          polyline: true,
          data: linesRoute,
          lineStyle: { color: 'transparent', width: 6, opacity: 1 },
          effect: {
            period: 6,
            show: true,
            symbol: 'react',
            color: '#000',
            symbolSize: [6, 10],
            trailLength: 0.8,
            loop: true
          },
          animation: false,
          zlevel: 13
        }]
    }

    const myChart = this.myChart;
    myChart.setOption(option)

    // this.effectID = setInterval(
    //   () => this.genEffect(silentSites),
    //   8000
    // );
  }

  genEffect (data) {
    const myChart = this.myChart;
    const series ={
      name: '站点',
      type: 'scatter',
      coordinateSystem: 'bmap',
      data: _.sampleSize(data,4).map(item=>Object.assign({}, item, {label:{show:true,color:'#fff', formatter:'{b}'}})),
      symbolSize: 5,
      itemStyle: { color: '#00BAFF' },
      zlevel: 43
    }
    myChart.setOption({ series })
  }

  render () {
    const { width = "100%", height = "100%" } = this.props
    return <div ref={ID => this.ID = ID} style={{ width, height }}></div>
  }
}